package org.ruixue.service;

import cn.rkylin.oms.common.dto.DBLog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.ruixue.dao.oms.EcItemMapper;
import org.ruixue.dao.oms.ShopMapper;
import org.ruixue.entity.oms.EcItem;
import org.ruixue.entity.oms.Shop;
import org.ruixue.request.ItemRequest;
import org.ruixue.request.UpdateStockRequest;
import org.ruixue.response.BaseResponse;
import org.ruixue.util.DateUtil;
import org.ruixue.util.HttpUtil;
import org.ruixue.util.LogUtil;
import org.ruixue.vo.ItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.commons.lang3.StringUtils.isBlank;

@Service("stockService")
public class StockService {

	@Value("${oms.address}")
	String omsUrl;

	@Autowired
	LogUtil logUtil;

	@Autowired
	ShopMapper shopMapper;

	@Autowired
	EcItemMapper ecItemMapper;

	@Autowired
	ItemService itemService;

	private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 商品同步库存 按店铺
	 *
	 * @param shopId
	 * @return
	 */
	public BaseResponse synchStockYiItem(String shopId) throws Exception {

		if (isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		ItemVO searchItemVO = new ItemVO();
		searchItemVO.setShopId(shop.getShopId());
		List<ItemVO> itemDataList = ecItemMapper.selectDataForSynchStock(searchItemVO);
		if (itemDataList.size() <= 0) {
			return new BaseResponse("false", "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)");
		}

		String allErrMsg = "";
		// 平台商品列表
		for (ItemVO itemData : itemDataList) {
			String errMsg = "";
			long sumStorage = 0; // 库存数合计
			ItemVO searchItemSkuVO = new ItemVO();
			searchItemSkuVO.setShopId(shopId);
			searchItemSkuVO.setEcItemId(itemData.getEcItemId());
			List<ItemVO> itemSkuList = ecItemMapper.selectSkuForSynchStock(searchItemSkuVO);
			String autoList = itemData.getAutoList();

			// 平台商品SKU列表
			for (ItemVO itemSku : itemSkuList) {
				Map<String, Object> resultMap = this.synchStock(shop, itemSku);
				String msg = (String) resultMap.get("msg");
				if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
					return new BaseResponse("false", msg);
				}
				errMsg = errMsg + resultMap.get("msg");
				sumStorage = sumStorage + Long.parseLong(resultMap.get("storage").toString());
			}

			if ("".equals(errMsg)) {
				// 平台商品上下架
				if (sumStorage <= 0) { // 下架
					errMsg = errMsg + listDelist(shop, itemData, false, 0);
				} else if ("y".equals(autoList) && sumStorage > 0) { // 上架
					errMsg = errMsg + listDelist(shop, itemData, true, sumStorage);
				}
			}
			allErrMsg = allErrMsg + errMsg;
		}
		if (StringUtils.isNotEmpty(allErrMsg)) {
			return new BaseResponse("false", allErrMsg);
		}
		return new BaseResponse();
	}

	/**
	 * 同步店铺库存并上下架
	 *
	 * @param itemSku
	 * @return 错误消息
	 * @throws Exception
	 *             异常
	 */
	private Map<String, Object> synchStock(Shop shop, ItemVO itemSku) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String returnMsg = "";
		int storage = 0; // 库存数

		// 获取平台商品库存数
		String requestUrl = omsUrl + "/item/getPlatformStockCount.action";
		String reqParams = JSON.toJSONString(itemSku);
		String resJson = HttpUtil.sendByPostJson(requestUrl, reqParams);
		JSONObject jsonObject = JSON.parseObject(resJson, JSONObject.class);
		// 接收返回值
		storage = (int) jsonObject.get("storage");
		returnMsg = jsonObject.get("msg").toString();

		if ("".equals(returnMsg)) {
			// 库存同步
			UpdateStockRequest updateStockRequest = new UpdateStockRequest();
			updateStockRequest.setEcItemCode(itemSku.getEcItemCode());
			String ecSkuCode = itemSku.getEcSkuCode();
			if (ecSkuCode != null && "0".equals(ecSkuCode)) {
				ecSkuCode = null;
			}
			updateStockRequest.setEcSkuCode(ecSkuCode);
			updateStockRequest.setStockCount(String.valueOf(storage));

			// 调用修改平台商城-商品表库存
			BaseResponse baseResponse = itemService.updateYiSkuStock(shop.getShopId(), updateStockRequest);
			if (baseResponse.getSuccess().equals("false")) {
				logUtil.info(new DBLog(itemSku.getEcSkuCode(), "", "synchStock", DateUtil.getCurrentDateStr()
						+ " 自动同步库存平台规格编码为【" + itemSku.getEcSkuCode() + "】同步失败," + baseResponse.getMsg()));
				returnMsg = returnMsg + "平台规格编码:" + itemSku.getEcSkuCode() + baseResponse.getMsg() + "\\n";
			}
		}
		returnMap.put("msg", returnMsg);
		returnMap.put("storage", storage);
		return returnMap;
	}

	/**
	 * 商品上下架
	 *
	 * @param itemData
	 *            平台商品VO
	 * @param listFlg
	 *            上架FLG(true:上架,false:下架)
	 * @param sumStorage
	 *            商品库存数
	 * @return 错误消息
	 * @throws Exception
	 *             异常
	 */
	@SuppressWarnings("unchecked")
	private String listDelist(Shop shop, ItemVO itemData, boolean listFlg, long sumStorage) throws Exception {
		String errMsg = "";
		String ecItemCode = itemData.getEcItemCode();
		String url = omsUrl;
		String requestParams = "";
		EcItem item = new EcItem();
		item.setShopId(shop.getShopId());
		BaseResponse baseResponse = null;
		if (listFlg) {
			// 上架
			item.setEcItemCode(ecItemCode);
			item.setApproveStatus("上架");
			item.setListTime(new Date());

			ItemRequest listingItemRequest = new ItemRequest();
			listingItemRequest.setEcItemCode(ecItemCode);
			// listingItemRequest.setStockCount(String.valueOf(sumStorage));
			baseResponse = itemService.listingYiItem(shop.getShopId(), listingItemRequest);

		} else {
			// 下架
			item.setEcItemCode(ecItemCode);
			item.setApproveStatus("下架");
			item.setDelistTime(new Date());

			ItemRequest delistingItemRequest = new ItemRequest();
			delistingItemRequest.setEcItemCode(ecItemCode);
			baseResponse = itemService.delistingYiItem(shop.getShopId(), delistingItemRequest);

		}
		if (baseResponse.getSuccess().equals("true")) {
			ecItemMapper.updateByPrimaryKeySelectiveEcItem(item);
		} else {
			logUtil.info(new DBLog(ecItemCode, "", "synchStock",
					DateUtil.getCurrentDateStr() + " 同步库存平台商品编码为【" + ecItemCode + "】同步失败," + baseResponse.getMsg()));
			errMsg = errMsg + "平台商品编码:" + ecItemCode + baseResponse.getMsg() + "\\n";
		}
		return errMsg;
	}

	/**
	 * 商品同步库存 根据商品
	 *
	 * @param shopId
	 * @param ecItemId
	 * @return
	 */
	public BaseResponse synchStockYiItemByItem(String shopId, String ecItemId) throws Exception {
		if (isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}
		String allErrMsg = "";
		ItemVO searchItemVO = new ItemVO();
		searchItemVO.setEcItemId(ecItemId);
		List<ItemVO> itemDataList = ecItemMapper.selectDataForSynchStock(searchItemVO);
		if (itemDataList.size() > 0) {
			// 平台商品列表
			for (ItemVO itemData : itemDataList) {
				String errMsg = "";
				long sumStorage = 0; // 库存数合计
				ItemVO searchItemSkuVO = new ItemVO();
				searchItemSkuVO.setShopId(itemData.getShopId());
				searchItemSkuVO.setEcItemId(itemData.getEcItemId());
				List<ItemVO> itemSkuList = ecItemMapper.selectSkuForSynchStock(searchItemSkuVO);
				// 平台商品SKU列表
				for (ItemVO itemSku : itemSkuList) {
					Map<String, Object> resultMap = this.synchStock(shop, itemSku);
					String msg = (String) resultMap.get("msg");
					if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
						return new BaseResponse("false", msg);
					}
					errMsg = errMsg + resultMap.get("msg");
					sumStorage = sumStorage + Long.parseLong(resultMap.get("storage").toString());
				}
				if ("".equals(errMsg)) {
					// 平台商品上下架
					if (sumStorage <= 0) { // 下架
						errMsg = errMsg + listDelist(shop, itemData, false, sumStorage);
					}
				}
				allErrMsg = allErrMsg + errMsg;
			}
		} else {
			EcItem ecItemModel = ecItemMapper.selectByEcItemIdEcItem(ecItemId);
			allErrMsg = "平台商品编码:" + ecItemModel.getEcItemCode() + "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)\\n";
		}
		if (StringUtils.isNotEmpty(allErrMsg)) {
			return new BaseResponse("false", allErrMsg);
		}
		return new BaseResponse();
	}

	/**
	 * 商品同步库存 根据sku
	 *
	 * @param shopId
	 * @param ecSkuId
	 * @return
	 */
	public BaseResponse synchStockYiItemBySku(String shopId, String ecSkuId) throws Exception {
		if (isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}
		// 按平台商品SKU同步库存
		String errMsg = "";
		ItemVO searchItemVO = new ItemVO();
		searchItemVO.setEcSkuId(ecSkuId);
		List<ItemVO> itemSkuList = ecItemMapper.selectSkuForSynchStock(searchItemVO);

		if (itemSkuList.size() > 0) {
			// 平台商品SKU列表
			for (ItemVO itemSku : itemSkuList) {
				Map<String, Object> resultMap = this.synchStock(shop, itemSku);
				String msg = (String) resultMap.get("msg");
				if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
					return new BaseResponse("false", msg);
				}
				errMsg = errMsg + resultMap.get("msg");
			}
		} else {
			errMsg = "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)";
		}
		if (StringUtils.isNotEmpty(errMsg)) {
			return new BaseResponse("false", errMsg);
		}
		return new BaseResponse();
	}
}
